﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using MyBasicLib.Reflection;

namespace MyBasicLib.Data.ORMLiteNew
{
    public interface ITable
    { }
    public interface IMappingProvider
    {
        bool IsValidTableClass(Type type);
        TableAttribute GetTableAttribute(Type type);
        ColumnAttribute GetColumnAttribute(PropertyInfo propertyInfo);
    }
    public class AttributeMappingProvider : IMappingProvider
    {
        public bool IsValidTableClass(Type type)
        {
            return type.IsDefined(typeof(TableAttribute), true);
        }
        public TableAttribute GetTableAttribute(Type type)
        {
            return type.GetCustomAttributes(typeof(TableAttribute), true).FirstOrDefault()
                as TableAttribute;
        }

        public ColumnAttribute GetColumnAttribute(Type type, string propertyName)
        {
            return type.GetProperty(propertyName).
                GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault()
                  as ColumnAttribute;
        }


        public ColumnAttribute GetColumnAttribute(PropertyInfo propertyInfo)
        {
            return (propertyInfo.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault()
                  as ColumnAttribute)??new ColumnAttribute() ;
        }
    }

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
    public sealed class TableAttribute : Attribute
    {
        public String TableName { get; set; }
        public String KeyName { get; set; } //"key1,key2"         
    }

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public sealed class ColumnAttribute : Attribute
    {
        public String ColumnName { get; set; }
        public Type ColumnType { get; set; }
        public Int32? MaxSize { get; set; }

        public Boolean IsDbGenerated { get; set; }
        public Object DefaultValue { get; set; }
    }

    /// <summary>
    /// 用在有默认值且不能手动指定值的字段,如自增列
    /// </summary> 
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public sealed class DbGeneratedAttribute : Attribute
    {
        // public object   DefaultValue { get; set; }
    }
}
